<template>
  <div class="points-exchange-container">
    <div class="header">
      <h2>积分兑换商城</h2>
      <div class="header-actions">
        <el-button @click="showAddDialog" type="primary" icon="el-icon-plus">添加商品</el-button>
        <el-button @click="refreshData" icon="el-icon-refresh">刷新</el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <div class="stat-card">
        <div class="stat-icon">
          <i class="el-icon-goods"></i>
        </div>
        <div class="stat-content">
          <h3>{{ stats.totalProducts || 0 }}</h3>
          <p>总商品数</p>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon">
          <i class="el-icon-check"></i>
        </div>
        <div class="stat-content">
          <h3>{{ stats.activeProducts || 0 }}</h3>
          <p>上架商品</p>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon">
          <i class="el-icon-box"></i>
        </div>
        <div class="stat-content">
          <h3>{{ stats.inStockProducts || 0 }}</h3>
          <p>有库存商品</p>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon">
          <i class="el-icon-coin"></i>
        </div>
        <div class="stat-content">
          <h3>{{ Math.round(stats.avgPointsRequired || 0) }}</h3>
          <p>平均所需积分</p>
        </div>
      </div>
    </div>

    <!-- 搜索筛选 -->
    <div class="search-container">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="商品名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入商品名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="商品分类">
          <el-select v-model="searchForm.category" placeholder="请选择分类" clearable>
            <el-option label="实物商品" value="PHYSICAL"></el-option>
            <el-option label="虚拟商品" value="VIRTUAL"></el-option>
            <el-option label="优惠券" value="COUPON"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品类型">
          <el-select v-model="searchForm.productType" placeholder="请选择类型" clearable>
            <el-option label="商品" value="GOODS"></el-option>
            <el-option label="折扣券" value="DISCOUNT_COUPON"></el-option>
            <el-option label="免邮券" value="FREE_SHIPPING"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.isActive" placeholder="请选择状态" clearable>
            <el-option label="上架" :value="true"></el-option>
            <el-option label="下架" :value="false"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchData" >搜索</el-button>
          <el-button @click="resetSearch" >重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 商品列表 -->
    <div class="table-container">
      <el-table
        :data="tableData"
        v-loading="loading"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="imageUrl" label="商品图片" width="100">
          <template slot-scope="scope">
            <el-image
              v-if="scope.row.imageUrl"
              :src="scope.row.imageUrl"
              :preview-src-list="[scope.row.imageUrl]"
              style="width: 60px; height: 60px"
              fit="cover"
            />
            <div v-else class="no-image">
              <i class="el-icon-picture"></i>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="商品名称" min-width="150">
          <template slot-scope="scope">
            <div class="product-name">
              <span>{{ scope.row.name }}</span>
              <small v-if="scope.row.description">{{ scope.row.description }}</small>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="分类" width="100">
          <template slot-scope="scope">
            <el-tag :type="getCategoryColor(scope.row.category)">
              {{ getCategoryText(scope.row.category) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="productType" label="类型" width="120">
          <template slot-scope="scope">
            <el-tag :type="getProductTypeColor(scope.row.productType)">
              {{ getProductTypeText(scope.row.productType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="pointsRequired" label="所需积分" width="120" sortable>
          <template slot-scope="scope">
            <span class="points-required">{{ scope.row.pointsRequired }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="originalPrice" label="原价" width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.originalPrice">¥{{ scope.row.originalPrice }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="stockQuantity" label="库存" width="100">
          <template slot-scope="scope">
            <span :class="{'low-stock': scope.row.stockQuantity < 10}">
              {{ scope.row.stockQuantity }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="isActive" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isActive ? 'success' : 'danger'">
              {{ scope.row.isActive ? '上架' : '下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sortOrder" label="排序" width="80"></el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="editProduct(scope.row)"
              type="text"
            >
              编辑
            </el-button>
            <el-button
              size="mini"
              @click="toggleStatus(scope.row)"
              type="text"
              :icon="scope.row.isActive ? 'el-icon-close' : 'el-icon-check'"
            >
              {{ scope.row.isActive ? '下架' : '上架' }}
            </el-button>
            <el-button
              size="mini"
              @click="adjustStock(scope.row)"
              type="text"
              icon="el-icon-box"
            >
              调库存
            </el-button>
            <el-button
              size="mini"
              @click="deleteProduct(scope.row)"
              type="text"
              style="color: #f56c6c"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        />
      </div>
    </div>

    <!-- 添加/编辑商品对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="800px"
      @close="closeDialog"
    >
      <el-form
        :model="productForm"
        :rules="productRules"
        ref="productForm"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="productForm.name" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所需积分" prop="pointsRequired">
              <el-input-number
                v-model="productForm.pointsRequired"
                :min="1"
                :max="999999"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品分类" prop="category">
              <el-select v-model="productForm.category" placeholder="请选择分类" style="width: 100%">
                <el-option label="实物商品" value="PHYSICAL"></el-option>
                <el-option label="虚拟商品" value="VIRTUAL"></el-option>
                <el-option label="优惠券" value="COUPON"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品类型" prop="productType">
              <el-select v-model="productForm.productType" placeholder="请选择类型" style="width: 100%">
                <el-option label="商品" value="GOODS"></el-option>
                <el-option label="折扣券" value="DISCOUNT_COUPON"></el-option>
                <el-option label="免邮券" value="FREE_SHIPPING"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="原价" prop="originalPrice">
              <el-input-number
                v-model="productForm.originalPrice"
                :min="0"
                :precision="2"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存数量" prop="stockQuantity">
              <el-input-number
                v-model="productForm.stockQuantity"
                :min="0"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="商品描述">
          <el-input
            v-model="productForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入商品描述"
          />
        </el-form-item>
        
        <el-form-item label="商品图片">
          <el-input v-model="productForm.imageUrl" placeholder="请输入图片URL" />
        </el-form-item>
        
        <!-- 优惠券相关字段 -->
        <div v-if="productForm.productType === 'DISCOUNT_COUPON' || productForm.productType === 'FREE_SHIPPING'">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="折扣率(%)">
                <el-input-number
                  v-model="productForm.discountRate"
                  :min="0"
                  :max="100"
                  :precision="2"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="有效期(天)">
                <el-input-number
                  v-model="productForm.validityDays"
                  :min="1"
                  :max="365"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="最低消费金额">
                <el-input-number
                  v-model="productForm.minOrderAmount"
                  :min="0"
                  :precision="2"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="最大折扣金额">
                <el-input-number
                  v-model="productForm.maxDiscountAmount"
                  :min="0"
                  :precision="2"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排序">
              <el-input-number
                v-model="productForm.sortOrder"
                :min="0"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否上架">
              <el-switch v-model="productForm.isActive" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveProduct">保存</el-button>
      </div>
    </el-dialog>

    <!-- 库存调整对话框 -->
    <el-dialog
      title="调整库存"
      :visible.sync="stockDialogVisible"
      width="400px"
    >
      <el-form :model="stockForm" label-width="100px">
        <el-form-item label="商品名称">
          <span>{{ stockForm.productName }}</span>
        </el-form-item>
        <el-form-item label="当前库存">
          <span>{{ stockForm.currentStock }}</span>
        </el-form-item>
        <el-form-item label="调整数量">
          <el-input-number
            v-model="stockForm.adjustAmount"
            :min="-stockForm.currentStock"
            style="width: 100%"
          />
          <small>正数为增加，负数为减少</small>
        </el-form-item>
        <el-form-item label="调整原因">
          <el-input
            v-model="stockForm.reason"
            type="textarea"
            :rows="2"
            placeholder="请输入调整原因"
          />
        </el-form-item>
      </el-form>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="stockDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveStockAdjustment">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'PointsExchange',
  data() {
    return {
      loading: false,
      tableData: [],
      currentPage: 1,
      pageSize: 20,
      total: 0,
      searchForm: {
        name: '',
        category: '',
        productType: '',
        isActive: null
      },
      stats: {},
      dialogVisible: false,
      dialogTitle: '',
      productForm: {
        id: null,
        name: '',
        description: '',
        imageUrl: '',
        pointsRequired: 100,
        originalPrice: 0,
        stockQuantity: 0,
        category: 'VIRTUAL',
        productType: 'GOODS',
        discountRate: null,
        validityDays: 30,
        minOrderAmount: null,
        maxDiscountAmount: null,
        isActive: true,
        sortOrder: 0
      },
      productRules: {
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        pointsRequired: [
          { required: true, message: '请输入所需积分', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择商品分类', trigger: 'change' }
        ],
        productType: [
          { required: true, message: '请选择商品类型', trigger: 'change' }
        ]
      },
      stockDialogVisible: false,
      stockForm: {
        productId: null,
        productName: '',
        currentStock: 0,
        adjustAmount: 0,
        reason: ''
      }
    }
  },
  mounted() {
    this.loadData()
    this.loadStats()
  },
  methods: {
    async loadData() {
      this.loading = true
      try {
        const params = {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          ...this.searchForm
        }
        
        const response = await this.request.get('/api/member/exchange/products/admin', { params })
        if (response.code === '200') {
          this.tableData = response.data.records
          this.total = response.data.total
        } else {
          this.$message.error(response.msg || '加载数据失败')
        }
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$message.error('加载数据失败')
      } finally {
        this.loading = false
      }
    },
    
    async loadStats() {
      try {
        const response = await this.request.get('/api/member/exchange/products/stats')
        if (response.code === '200') {
          this.stats = response.data
        } else {
          this.$message.error(response.msg || '加载统计数据失败')
        }
      } catch (error) {
        console.error('加载统计数据失败:', error)
        // 如果接口失败，使用本地计算的统计数据
        this.stats = {
          totalProducts: this.tableData.length,
          activeProducts: this.tableData.filter(p => p.isActive).length,
          inStockProducts: this.tableData.filter(p => p.stockQuantity > 0).length,
          avgPointsRequired: this.tableData.reduce((sum, p) => sum + p.pointsRequired, 0) / this.tableData.length || 0
        }
      }
    },
    
    searchData() {
      this.currentPage = 1
      this.loadData()
    },
    
    resetSearch() {
      this.searchForm = {
        name: '',
        category: '',
        productType: '',
        isActive: null
      }
      this.currentPage = 1
      this.loadData()
    },
    
    refreshData() {
      this.loadData()
      this.loadStats()
    },
    
    handleSizeChange(val) {
      this.pageSize = val
      this.loadData()
    },
    
    handleCurrentChange(val) {
      this.currentPage = val
      this.loadData()
    },
    
    showAddDialog() {
      this.dialogTitle = '添加商品'
      this.productForm = {
        id: null,
        name: '',
        description: '',
        imageUrl: '',
        pointsRequired: 100,
        originalPrice: 0,
        stockQuantity: 0,
        category: 'VIRTUAL',
        productType: 'GOODS',
        discountRate: null,
        validityDays: 30,
        minOrderAmount: null,
        maxDiscountAmount: null,
        isActive: true,
        sortOrder: 0
      }
      this.dialogVisible = true
    },
    
    editProduct(row) {
      this.dialogTitle = '编辑商品'
      this.productForm = { ...row }
      this.dialogVisible = true
    },
    
    closeDialog() {
      this.dialogVisible = false
      this.$refs.productForm.resetFields()
    },
    
    async saveProduct() {
      try {
        await this.$refs.productForm.validate()
        
        const url = this.productForm.id 
          ? `/api/member/exchange/products/${this.productForm.id}`
          : '/api/member/exchange/products'
        
        const method = this.productForm.id ? 'put' : 'post'
        
        const response = await this.request[method](url, this.productForm)
        if (response.code === '200') {
          this.$message.success(this.productForm.id ? '更新成功' : '添加成功')
          this.dialogVisible = false
          // 如果是新增商品，重置到第一页
          if (!this.productForm.id) {
            this.currentPage = 1
          }
          this.loadData()
          this.loadStats()
        } else {
          this.$message.error(response.msg || '保存失败')
        }
      } catch (error) {
        console.error('保存商品失败:', error)
        this.$message.error('保存失败')
      }
    },
    
    async toggleStatus(row) {
      try {
        const action = row.isActive ? '下架' : '上架'
        await this.$confirm(`确定要${action}此商品吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await this.request.put(`/api/member/exchange/products/${row.id}`, {
          ...row,
          isActive: !row.isActive
        })
        
        if (response.code === '200') {
          this.$message.success(`${action}成功`)
          this.loadData()
        } else {
          this.$message.error(response.msg || `${action}失败`)
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('操作失败:', error)
          this.$message.error('操作失败')
        }
      }
    },
    
    adjustStock(row) {
      this.stockForm = {
        productId: row.id,
        productName: row.name,
        currentStock: row.stockQuantity,
        adjustAmount: 0,
        reason: ''
      }
      this.stockDialogVisible = true
    },
    
    async saveStockAdjustment() {
      try {
        if (this.stockForm.adjustAmount === 0) {
          this.$message.warning('请输入调整数量')
          return
        }
        
        const response = await this.request.post('/api/member/exchange/products/adjust-stock', {
          productId: this.stockForm.productId,
          adjustAmount: this.stockForm.adjustAmount,
          reason: this.stockForm.reason
        })
        
        if (response.code === '200') {
          this.$message.success('库存调整成功')
          this.stockDialogVisible = false
          this.loadData()
        } else {
          this.$message.error(response.msg || '库存调整失败')
        }
      } catch (error) {
        console.error('库存调整失败:', error)
        this.$message.error('库存调整失败')
      }
    },
    
    async deleteProduct(row) {
      try {
        await this.$confirm('确定要删除此商品吗？删除后无法恢复！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await this.request.delete(`/api/member/exchange/products/${row.id}`)
        if (response.code === '200') {
          this.$message.success('删除成功')
          this.loadData()
        } else {
          this.$message.error(response.msg || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
        }
      }
    },
    
    getCategoryText(category) {
      const categoryMap = {
        'PHYSICAL': '实物商品',
        'VIRTUAL': '虚拟商品',
        'COUPON': '优惠券'
      }
      return categoryMap[category] || category
    },
    
    getCategoryColor(category) {
      const colorMap = {
        'PHYSICAL': 'success',
        'VIRTUAL': 'primary',
        'COUPON': 'warning'
      }
      return colorMap[category] || 'info'
    },
    
    getProductTypeText(type) {
      const typeMap = {
        'GOODS': '商品',
        'DISCOUNT_COUPON': '折扣券',
        'FREE_SHIPPING': '免邮券'
      }
      return typeMap[type] || type
    },
    
    getProductTypeColor(type) {
      const colorMap = {
        'GOODS': 'success',
        'DISCOUNT_COUPON': 'warning',
        'FREE_SHIPPING': 'info'
      }
      return colorMap[type] || 'info'
    }
  }
}
</script>

<style scoped>
.points-exchange-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.header h2 {
  margin: 0;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  display: flex;
  align-items: center;
  gap: 15px;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
}

.stat-content h3 {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.stat-content p {
  margin: 5px 0 0 0;
  color: #666;
  font-size: 14px;
}

.search-container {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

.search-form {
  margin: 0;
}

.table-container {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.no-image {
  width: 60px;
  height: 60px;
  background: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ccc;
  font-size: 20px;
  border-radius: 4px;
}

.product-name {
  display: flex;
  flex-direction: column;
}

.product-name small {
  color: #999;
  font-size: 12px;
  margin-top: 4px;
}

.points-required {
  color: #409eff;
  font-weight: bold;
}

.low-stock {
  color: #f56c6c;
  font-weight: bold;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .points-exchange-container {
    padding: 10px;
  }
  
  .header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
  
  .stats-cards {
    grid-template-columns: 1fr;
  }
  
  .search-form {
    display: flex;
    flex-direction: column;
  }
  
  .search-form .el-form-item {
    margin-bottom: 15px;
  }
}
</style> 